﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinCalcManager;
using Infragistics.Win.CalcEngine;
using WeifenLuo.WinFormsUI.Docking;
using cfg = System.Configuration;
using GoldPrinter;
using Infragistics.Excel;
using System.IO;

namespace BYManageInfoSystem
{
//     ( 59998.50 - 18159.34 )  * ( 6.310144 - 0.085 ) * 1.17 /1.04 - 41839.16 * 6.310144
//前面是价税合计( 59998.50 - 18159.34 )  * ( 6.310144 - 0.085 ) * 1.17 /1.04，后面是退税本金 41839.16 * 6.310144
// ( 2499987.98 - 281283.41 )  * 0.8123 / 6.3091 * ( 6.3091 - 0.085 ) * 1.17 /1.01 - 2218704.57 * 0.8123
//( 2499987.98 - 281283.41 ) 港币
// ( 2499987.98 - 281283.41 )  * 0.8123 / 6.3091这里是港币转换成人民币再美元
// ( 2499987.98 - 281283.41 )  * 0.8123 / 6.3091 * ( 6.3091 - 0.085 )这里再转成人民币，之所以这样是因为0.085，0.095这个是美元订的系数。
// ( 2499987.98 - 281283.41 )  * 0.8123 / 6.3091 * ( 6.3091 - 0.085 ) * 1.17 /1.01这里是国家订的退税点，跟工厂出口产品有关。
//2218704.57 * 0.8123这个是退税本金
//加税合计-退税本金=到厂退税款



            //退税大方面分2种情况，每种情况都有一定的复杂点
        //1.本次收款余额 > 全部审票，审票全退完，是简单之处，复杂点是收款不能一次退完。
        //2.本次收款余额 < 全部审票，收款全退完，是简单之处，复杂点是审票要按顺序退。相对来说2更简单些。 

//必要信息

//1.本次付税本金--收款币制
//2.本次收款余额--收款币制
//3.if(本次付税本金 >= 本次收款余额)，本次收款全部退完
//3.1 该收款编号前几次退税本金的枚举。到收款补充表里面按收款编号去查，如果只有一条自序号为0的记录，则说明之前没有退过税；如果有2条记录，取第一条记录的已经退税值。
//3.2 审票方面，查询审票补充表，按顺序退税。
//3.2.1审票退税顺序
//     //排序
//            //1.获得该工厂正常退税点
//            //2.找出特殊退税点，并记录FinCheckInvoiceRecordDetailTab_Newid，特殊退税点退税顺序，金额由小到大
//            //3.先退特殊退税点的FinCheckInvoiceRecordDetailTab_Newid，接着按审票记录登记先后顺序退。

    //    1.先退上次动过的，及上次动过之前的审票（做为一个整体考察）									
    //2.找到1中的集合后，先退特殊退税点的									
    //3.还要考察后面的，如果能和前面合并的，要和前面合并退（可能合并特殊退税的，也可能合并正常退税的）。									

//假设这样一种情况：3个审票。1个收款
//收款10000

//（1）10000，正常退税点；5000特殊退税点
//（2）10000，正常退税点；5000特殊退税点
//（3）10000，正常退税点；5000特殊退税点
//则本次退税结束后，审票变为
//（1）10000，正常退税点（未退）；5000特殊退税点（已经退完）
//（2）10000，正常退税点（未退）；5000特殊退税点（已经退完）
//（3）10000，正常退税点（未退）；5000特殊退税点（未退）
//那么假设又有一笔10000的收款，此时再退税的话
//是先退（1）的10000，还是先退（3）的5000，然后再在（1）退5000.
//---------------------------
//我们现在是这样的，如果审票日期是同一天，就把它们视为一个整体，按照你上面的说法，是应该先退（3）的5000，然后再在（1）退5000；
//如果上面的审票是（1）（2）是同一天，而（3）是之后再审的，就先退（1）的10000，无论（3）有多少个特殊退税点，都先退完（1）（2）先
//这样是为了防止不断地先退特殊退税
//--------------------------------
//4if(本次付税本金 < 本次收款余额)，本次审票全部退完
//4.1 该收款编号前几次退税本金的枚举。到收款补充表里面按收款编号去查，如果只有一条自序号为0的记录，则说明之前没有退过税；如果有2条记录，取第一条记录的已经退税值。

//是否特殊工厂很重要


    public partial class Frm_PayAndRecvTab : DockContent
    {
        private class FinCheckInvoiceRecordDetailAuxiliaryTabInfo
        {
            public Decimal dtInvoicYue;
            public int nFinCheckInvoiceRecordDetailTabID;
        }
        //public enum IsSpecFac
        //{
        //    unknown = 0,
        //    yes = 1,
        //    no = 2           
        //}
        //DataTable m_dt = new DataTable(); 
        //private IsSpecFac m_IsSpecFac = IsSpecFac.unknown;
        private bool m_bIsExportAllColumn = false;
        Infragistics.Win.UltraWinGrid.UltraGridRow[] m_ugr = null;
        private bool m_bSumStart = false;
        Color m_color = new Color();
        private DGBY.BLL.SJPackingTab m_bllSJPackingTab = new DGBY.BLL.SJPackingTab();
        public static DGBY.BLL.TaoDaPrinterNameTab bllTaoDaPrinterNameTab = new DGBY.BLL.TaoDaPrinterNameTab();

        protected string templetFilePath = cfg.ConfigurationSettings.AppSettings["TempletFilePath"];
        private Hashtable m_SQLStringList = new Hashtable();
        private ArrayList m_arrayList = new ArrayList();
     //   private bool m_bCanModify = true;
        private DGBY.BLL.FinAbstractTab m_bllFinAbstractTab = new DGBY.BLL.FinAbstractTab();
        private DGBY.BLL.FinRecvMoneyDetailTab_New m_bllFinRecvMoneyDetailTab_New = new DGBY.BLL.FinRecvMoneyDetailTab_New();
        private DGBY.BLL.FinCheckInvoiceRecordDetailTab_New m_bllFinCheckInvoiceRecordDetailTab_New = new DGBY.BLL.FinCheckInvoiceRecordDetailTab_New();
        private DGBY.BLL.FinRecvMoneyAuxiliaryTab_New m_bllFinRecvMoneyAuxiliaryTab_New = new DGBY.BLL.FinRecvMoneyAuxiliaryTab_New();
        private DGBY.BLL.FinCheckInvoiceRecordDetailAuxiliaryTab_New m_bllInvoiceAuxiliary_New
            = new DGBY.BLL.FinCheckInvoiceRecordDetailAuxiliaryTab_New();

        
        private int m_nSelectRowIndex = 0;
        private DGBY.BLL.FinDepRecvAndPayDetailTab_New m_bllFinDepRecvAndPayDetailTab_New = new DGBY.BLL.FinDepRecvAndPayDetailTab_New();
        private DGBY.BLL.FactoryGoodsTab m_bllFactoryGoodsTab = new DGBY.BLL.FactoryGoodsTab();

        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private DGBY.BLL.BiZhiTab m_bllBiZhiTab = new DGBY.BLL.BiZhiTab();
        private DGBY.BLL.FinRecvMoneyWayTab m_bllFinRecvMoneyWayTab = new DGBY.BLL.FinRecvMoneyWayTab();
        private DGBY.BLL.PaidanRegisterTab m_bllPaidanRegisterTab = new DGBY.BLL.PaidanRegisterTab();
        private int m_nDelIndex = -1;
        private int m_nDelbackgroundIndex = -1;
        private bool m_bInsertFlag = false;
        private bool m_bCopyInsertFlag = false;
        private DGBY.Model.FinDepRecvAndPayDetailTab_New m_modelFinDepRecvAndPayDetailTab_New = null;
        private DGBY.BLL.FinCheckInvoiceRecordDetailAuxiliaryTab_New m_bllFinCheckInvoiceRecordDetailAuxiliaryTab_New = new DGBY.BLL.FinCheckInvoiceRecordDetailAuxiliaryTab_New();
        private string m_strFolder = "d:/付税记录删除/";
  
        private ArrayList GGetRecvMoneyPayedTaxEnumRecord(DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New)
        {
            ArrayList al = new ArrayList();
            DataSet ds = m_bllFinRecvMoneyAuxiliaryTab_New.GetRecvMoneyPayedTaxEnumRecord(@"FinRecvMoneyAuxiliaryTab_New.IsPayTaxDone = 1 
                and FinRecvMoneyDetailTab_New.BianHao = '" + modelFinDepRecvAndPayDetailTab_New.RecvBianNo
         + "' and FinRecvMoneyDetailTab_New.FactoryDataTabID = '"
            + modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID.ToString() + "'");

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["PayedTaxMoneyValue"].ToString());
                    al.Add(dtTemp);
                }
            }

            return al;
        }

        public Frm_PayAndRecvTab()
        {
            InitializeComponent();
        }

        private Decimal GetRecvMoneyRemainNewTongji(string strWhere)
        {
            DataSet ds = m_bllFinDepRecvAndPayDetailTab_New.GetRecvMoneyRemainNewTongji(strWhere);
            Decimal dtTemp = 0;
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["RecvYuE"].ToString() != "")
                    dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[0]["RecvYuE"].ToString());
            }
            return dtTemp;
        }
        private Decimal GetRecvMoneyRemainNew(string strWhere)
        {
            DataSet ds = m_bllFinDepRecvAndPayDetailTab_New.GetRecvMoneyRemainNew(strWhere);
            Decimal dtTemp = 0;
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["RecvYuE"].ToString() != "")
                    dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[0]["RecvYuE"].ToString());
            }
            return dtTemp;
        }

        private Decimal GetRecvMoneyRemain(string strWhere)
        {
            DataSet ds = m_bllFinRecvMoneyAuxiliaryTab_New.GetRecvMoneyRemain(strWhere);
            Decimal dtTemp = 0;
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["RecvYuE"].ToString() != "")
                    dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[0]["RecvYuE"].ToString());
            }
            return dtTemp;
        }

        private Decimal GetInvoiceRemainTongji(string strWhere)
        {
            DataSet ds = m_bllInvoiceAuxiliary_New.GetInvoiceRemainTongji(strWhere);
            Decimal dtTemp = 0;
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["InvoiceYuE"].ToString() != "")
                    dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[0]["InvoiceYuE"].ToString());
            }
            return dtTemp;
        }
        private Decimal GetInvoiceRemain(string strWhere)
        {
            DataSet ds = m_bllInvoiceAuxiliary_New.GetInvoiceRemain(strWhere);
            Decimal dtTotal = 0;
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["InvoiceYuE"].ToString() != "")
                    {
                        Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["InvoiceYuE"].ToString());
                        dtTotal += dtTemp;
                    }
                }
            }
            return dtTotal;
        }

        private void ShowAllRecord(string strWhere)
        {


            DataSet ds = m_bllFinDepRecvAndPayDetailTab_New.GetList(strWhere);
            ultraGrid1.DataSource = null;

 

            DataSet dsTemp = m_bllFactoryDataTab.GetList("");

            this.ultraDropDownFac.DataSource = dsTemp.Tables[0];
            this.ultraDropDownFac.DisplayMember = "工厂简称";
            this.ultraDropDownFac.ValueMember = "FactoryDataTabID";
            this.ultraDropDownFac.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            for (int i = 0; i < this.ultraDropDownFac.DisplayLayout.Bands[0].Columns.Count; i++)
                this.ultraDropDownFac.DisplayLayout.Bands[0].Columns[i].Hidden = true;
            this.ultraDropDownFac.DisplayLayout.Bands[0].Columns["工厂简称"].Hidden = false;

            dsTemp = m_bllBiZhiTab.GetList("");

            this.ultraDropDownBiZhi.DataSource = dsTemp.Tables[0];
            this.ultraDropDownBiZhi.DisplayMember = "币制名称";
            this.ultraDropDownBiZhi.ValueMember = "BiZhiTabID";
            this.ultraDropDownBiZhi.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            for (int i = 0; i < this.ultraDropDownBiZhi.DisplayLayout.Bands[0].Columns.Count; i++)
                this.ultraDropDownBiZhi.DisplayLayout.Bands[0].Columns[i].Hidden = true;
            this.ultraDropDownBiZhi.DisplayLayout.Bands[0].Columns["币制名称"].Hidden = false;

            dsTemp = m_bllFinRecvMoneyWayTab.GetList("");

            this.ultraDropDownRecvWay.DataSource = dsTemp.Tables[0];
            this.ultraDropDownRecvWay.DisplayMember = "收款方式";
            this.ultraDropDownRecvWay.ValueMember = "FinRecvMoneyWayTabID";
            this.ultraDropDownRecvWay.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            for (int i = 0; i < this.ultraDropDownRecvWay.DisplayLayout.Bands[0].Columns.Count; i++)
                this.ultraDropDownRecvWay.DisplayLayout.Bands[0].Columns[i].Hidden = true;
            this.ultraDropDownRecvWay.DisplayLayout.Bands[0].Columns["收款方式"].Hidden = false;

            dsTemp = m_bllFinAbstractTab.GetList("");

            this.ultraDropDownAbs.DataSource = dsTemp.Tables[0];
            this.ultraDropDownAbs.DisplayMember = "摘要";
            this.ultraDropDownAbs.ValueMember = "FinAbstractTabID";
            this.ultraDropDownAbs.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            for (int i = 0; i < this.ultraDropDownAbs.DisplayLayout.Bands[0].Columns.Count; i++)
                this.ultraDropDownAbs.DisplayLayout.Bands[0].Columns[i].Hidden = true;
            this.ultraDropDownAbs.DisplayLayout.Bands[0].Columns["摘要"].Hidden = false;


            ultraGrid1.DataSource = ds.Tables[0];
            ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;

 
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["客户"].ValueList = this.ultraDropDownFac;
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["币种"].ValueList = this.ultraDropDownBiZhi;
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["收款方式"].ValueList = this.ultraDropDownRecvWay;
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["摘要"].ValueList = this.ultraDropDownAbs;
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["到厂货款公式"].CellMultiLine = Infragistics.Win.DefaultableBoolean.True;
        }

        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord("");
        }

        private Int64 MakeRecvMoneyDetailDJNo()
        {
            string strDate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString().PadLeft(2, '0') + System.DateTime.Now.Day.ToString().PadLeft(2, '0');
            DataSet ds = m_bllFinDepRecvAndPayDetailTab_New.GetSJPackDJNoByDate("DanJuDate = '" + strDate + "'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                string strDJNo = ds.Tables[0].Rows[0]["MaxJPackDJNum"].ToString();
                long nDJNo = 0;
                if (strDJNo != "")
                    nDJNo = Convert.ToInt64(strDJNo, 10);
                nDJNo++;
                string strTemp = "";
                if (strDJNo != "")
                    strTemp = string.Format("{0:d4}", nDJNo);
                else
                    strTemp = strDate + string.Format("{0:d4}", nDJNo);

                return Convert.ToInt64(strTemp, 10);
            }

            return 0;
        }
        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            InitColumnWidth();
            ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);
            ClassUltraGridCommonSet.LocalPrintPreveiw();
            //ClassUltraGridCommonSet.InitUltraWinGridRowNumSetting(e);
            foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                if (str == "编号" || str == "收款编号" || str == "摘要" || str == "客户" || str == "收款日期"
                    || str == "币种" || str == "外汇收入" || str == "当日牌价" || str == "外汇收入公式"
                    || str == "收款方式" || str == "单据日期" || str == "到厂货款" || str == "不参与退税")
                {
                    m_color = column2.CellAppearance.BackColor;
                    column2.CellAppearance.BackColor = Color.Coral;
                    column2.CellActivation = Activation.ActivateOnly;
                }

            }
            e.Layout.Override.RowSizing = RowSizing.AutoFree;
            e.Layout.Override.CellAppearance.TextVAlign = VAlign.Middle;
 
        }

        private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.Control)
            {

                if (!m_bInsertFlag)
                {
                    UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();
                    //  row.Cells[2] = DateTime.Parse("1900-01-01");
                }
            }
            switch (e.KeyCode)
            {

                case Keys.Up:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;     

                        string strTemp = this.ultraGrid1.ActiveCell.Column.Header.Caption;
                        if (strTemp == "摘要" || strTemp == "客户"
                            || strTemp == "币种" || strTemp == "收款方式")
                            return;
                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex > 0)
                            nIndex--;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.AboveCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Down:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;     

                        string strTemp = this.ultraGrid1.ActiveCell.Column.Header.Caption;
                        if (strTemp == "摘要" || strTemp == "客户" 
                            || strTemp == "币种" || strTemp == "收款方式")
                            return;
                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex < ultraGrid1.Rows.Count - 1)
                            nIndex++;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.BelowCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Right:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.NextCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
                case Keys.Left:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.PrevCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
            }
        }

        private void InitNewAddRowValueCopyContract(int nIndex)
        {



            UltraGridRow CurrentUGR = ultraGrid1.Rows[nIndex];
            CurrentUGR.Cells["单据日期"].Value = DateTime.Now.Date;
            CurrentUGR.Cells["收款日期"].Value = m_modelFinDepRecvAndPayDetailTab_New.RecvDate.Value;
            CurrentUGR.Cells["付款日期"].Value = DateTime.Now.Date;
            CurrentUGR.Cells["摘要"].Value = 1;
            CurrentUGR.Cells["客户"].Value = m_modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID;
            CurrentUGR.Cells["币种"].Value = m_modelFinDepRecvAndPayDetailTab_New.BiZhiTabID;
            CurrentUGR.Cells["收款方式"].Value = m_modelFinDepRecvAndPayDetailTab_New.FinRecvMoneyWayTabID;
            CurrentUGR.Cells["摘要"].Value = m_modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID;

            CurrentUGR.Cells["外汇收入"].Value = 0;
            CurrentUGR.Cells["当日牌价"].Value = m_modelFinDepRecvAndPayDetailTab_New.HuiLv;
            CurrentUGR.Cells["估计汇率"].Value = m_modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv;
            //CurrentUGR.Cells["付款编号"].Value = "";
            CurrentUGR.Cells["收款编号"].Value = m_modelFinDepRecvAndPayDetailTab_New.RecvBianNo;

            CurrentUGR.Cells["折合RMB"].Value = 0;
            CurrentUGR.Cells["付税本金"].Value = m_modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin;
            CurrentUGR.Cells["系数A"].Value = m_modelFinDepRecvAndPayDetailTab_New.FactorA;
            CurrentUGR.Cells["系数B"].Value = m_modelFinDepRecvAndPayDetailTab_New.FactorB;
            CurrentUGR.Cells["到厂货款"].Value = 0;
            CurrentUGR.Cells["备注"].Value = "";
            CurrentUGR.Cells["收水单日期"].Value = m_modelFinDepRecvAndPayDetailTab_New.RevcShuiDanDate;
            CurrentUGR.Cells["此次付款涉及的合同号集合"].Value = m_modelFinDepRecvAndPayDetailTab_New.ContractNoSets;
            CurrentUGR.Cells["是否已经打印"].Value = m_modelFinDepRecvAndPayDetailTab_New.IsPrint;

            CurrentUGR.Cells["编号"].Value = MakeRecvMoneyDetailDJNo();

            if (m_bInsertFlag)
            {
                ultraGrid1.Rows[nIndex].Cells[2].Activation = Activation.ActivateOnly;
                m_bInsertFlag = false;
                AddGoodsDetail(nIndex);

            }


        }
        private void InitNewAddRowValue(int nIndex)
        {
            UltraGridRow CurrentUGR = ultraGrid1.Rows[nIndex];
            CurrentUGR.Cells["单据日期"].Value = DateTime.Now.Date;
            CurrentUGR.Cells["收款日期"].Value = DateTime.Now.Date;
            CurrentUGR.Cells["付款日期"].Value = DateTime.Now.Date;
            CurrentUGR.Cells["摘要"].Value = 1;
            CurrentUGR.Cells["客户"].Value = 1;
            CurrentUGR.Cells["币种"].Value = 1;
            CurrentUGR.Cells["收款方式"].Value = 1;

            CurrentUGR.Cells["外汇收入"].Value = 0;
            CurrentUGR.Cells["当日牌价"].Value = 0;
            CurrentUGR.Cells["估计汇率"].Value = 0;
            //CurrentUGR.Cells["付款编号"].Value = "";
            CurrentUGR.Cells["收款编号"].Value = "";

            CurrentUGR.Cells["折合RMB"].Value = 0;
            CurrentUGR.Cells["付税本金"].Value = 0;
            CurrentUGR.Cells["系数A"].Value = 0;
            CurrentUGR.Cells["系数B"].Value = 0;
            CurrentUGR.Cells["到厂货款"].Value = 0;
            CurrentUGR.Cells["备注"].Value = "";
            CurrentUGR.Cells["编号"].Value = MakeRecvMoneyDetailDJNo();

            if (m_bInsertFlag)
            {
                ultraGrid1.Rows[nIndex].Cells[2].Activation = Activation.ActivateOnly;
                m_bInsertFlag = false;
                AddGoodsDetail(nIndex);
                   
            }

        }

        private void ultraGrid1_AfterRowInsert(object sender, RowEventArgs e)
        {
            ultraGrid1.Rows[e.Row.Index].Cells[1].IgnoreRowColActivation = true;
            ultraGrid1.Rows[e.Row.Index].Cells[1].Activation = Activation.AllowEdit;
            ultraGrid1.Rows[e.Row.Index].Cells[1].Activate();
            ultraGrid1.PerformAction(UltraGridAction.EnterEditMode);
            m_bInsertFlag = true;
            if (m_bCopyInsertFlag == false)
                InitNewAddRowValue(e.Row.Index);
            else
            {
                m_bCopyInsertFlag = false;
                InitNewAddRowValueCopyContract(e.Row.Index);
            }
            //InitNewAddRowValue(e.Row.Index);
        }

        private string GetWhereSets()
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();

            string strWhere = "";

            for (int i = 0; i < ugr.Length; i++)
            {

                //int nID = Convert.ToInt32(ugr[i].Cells[0].Value.ToString(), 10);
                if (ugr[i].Cells[0].Value.ToString() == "")
                    continue;
                strWhere += " or FinDepRecvAndPayDetailTab_NewID = '" + ugr[i].Cells[0].Value.ToString() + "'";

            }
            return strWhere;
        }
        //退税大方面分2种情况，每种情况都有一定的复杂点
        //1.本次收款余额 > 全部审票，审票全退完，是简单之处，复杂点是收款不能一次退完。
        //2.本次收款余额 < 全部审票，收款全退完，是简单之处，复杂点是审票要按顺序退。相对来说2更简单些。 
        private bool AddGoodsDetail(int nRowIndex)
        {

            try
            {
                m_SQLStringList.Clear();
                m_arrayList.Clear();
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];

                DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New = new DGBY.Model.FinDepRecvAndPayDetailTab_New();

                //modelFinDepRecvAndPayDetailTab_New.PayBianNo = CurrentUGR.Cells["付款编号"].Value.ToString();
                modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo = CurrentUGR.Cells["编号"].Value.ToString();

                modelFinDepRecvAndPayDetailTab_New.RecvBianNo = CurrentUGR.Cells["收款编号"].Value.ToString();
                modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo = CurrentUGR.Cells["编号"].Value.ToString();
                modelFinDepRecvAndPayDetailTab_New.Note = CurrentUGR.Cells["备注"].Value.ToString();
             
                DateTime dtTemp = (DateTime)CurrentUGR.Cells["收款日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.RecvDate = dtTemp.Date;
                dtTemp = (DateTime)CurrentUGR.Cells["付款日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.PayDate = dtTemp.Date;
                dtTemp = (DateTime)CurrentUGR.Cells["单据日期"].Value;

                dtTemp = (DateTime)CurrentUGR.Cells["收水单日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.RevcShuiDanDate = dtTemp.Date;
                modelFinDepRecvAndPayDetailTab_New.IsPrint = Convert.ToInt32(CurrentUGR.Cells["是否已经打印"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.ContractNoSets = CurrentUGR.Cells["此次付款涉及的合同号集合"].Value.ToString();

                modelFinDepRecvAndPayDetailTab_New.DanJuDate = System.DateTime.Now.Date;
                modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome = Convert.ToDecimal(CurrentUGR.Cells["外汇收入"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.ToRMB = Convert.ToDecimal(CurrentUGR.Cells["折合RMB"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.ToFacMoney = Convert.ToDecimal(CurrentUGR.Cells["到厂货款"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.FactorA = Convert.ToDecimal(CurrentUGR.Cells["系数A"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.FactorB = Convert.ToDecimal(CurrentUGR.Cells["系数B"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin = Convert.ToDecimal(CurrentUGR.Cells["付税本金"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv = Convert.ToDecimal(CurrentUGR.Cells["估计汇率"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.HuiLv = Convert.ToDecimal(CurrentUGR.Cells["当日牌价"].Value.ToString());

                //     modelFinDepRecvAndPayDetailTab_New.BYCompanyTabID = Convert.ToInt32(CurrentUGR.Cells["经营公司"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.BiZhiTabID = Convert.ToInt32(CurrentUGR.Cells["币种"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID = Convert.ToInt32(CurrentUGR.Cells["客户"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FinRecvMoneyWayTabID = Convert.ToInt32(CurrentUGR.Cells["收款方式"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID = Convert.ToInt32(CurrentUGR.Cells["摘要"].Value.ToString(), 10);

                ComputeToFacMoney(ref modelFinDepRecvAndPayDetailTab_New);
                m_bllFinDepRecvAndPayDetailTab_New.TransAdd(modelFinDepRecvAndPayDetailTab_New
                    , m_SQLStringList, m_arrayList);


                //CheckPayTaxModify(modelFinDepRecvAndPayDetailTab_New);
                m_bllSJPackingTab.ExecuteSqlTran(m_SQLStringList, m_arrayList);

                Frm_Main.Log2DB(this.Text, "增加", modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo);

                string strWhere = GetWhereSets();
                ShowAllRecord("FinDepRecvAndPayDetailTab_NewBianNo = '"
                    + modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo + "'" + strWhere);

                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private ArrayList ComputeComeToFacMoneyDiffBackTax(DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New)
        {
            ArrayList al = new ArrayList();
            DataSet dsTemp = m_bllFinRecvMoneyDetailTab_New.GetList("z1.不参与退税 = 0 and 编号 = '" + modelFinDepRecvAndPayDetailTab_New.RecvBianNo + "'");
            Decimal dtHuiLv = 0;
            if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 0)
            {
                dtHuiLv = Convert.ToDecimal(dsTemp.Tables[0].Rows[0]["汇率"].ToString());
                //Decimal dtRecvMoney = Convert.ToDecimal(dsTemp.Tables[0].Rows[0]["扣费后折算为USD"].ToString());
                //al.Add(dtRecvMoney);

            }
            Decimal dtBackTaxPoint = 0;
            DataSet dsInfo = m_bllFactoryGoodsTab.GetGoodsBandInfo("FactoryDataTab.FactoryDataTabID = '"
                + modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID.ToString() + "'");
            if (dsInfo.Tables.Count > 0 && dsInfo.Tables[0].Rows.Count > 0)
            {
                dtBackTaxPoint = 1.17m - Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["退税点"].ToString());
            }

            Decimal dtPayTaxBenJin = modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin * dtHuiLv;
            //Decimal dtPayTaxBenJin = modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin;
            DataSet ds = m_bllInvoiceAuxiliary_New.GetInvoiceEnumRecord(@"FinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0 
                and FactoryDataTab.FactoryDataTabID = '" + modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID.ToString() + "'");

            //这里是审票明细补充表
            //排序
            //1.获得该工厂正常退税点
            //2.找出特殊退税点，并记录FinCheckInvoiceRecordDetailTab_Newid，特殊退税点退税顺序，金额由小到大
            //3.先退特殊退税点的FinCheckInvoiceRecordDetailTab_Newid，接着按审票记录登记先后顺序退。
            //            1.先退上次动过的，及上次动过之前的审票（做为一个整体考察）									
            //2.找到1中的集合后，先退特殊退税点的									
            //3.还要考察后面的，如果能和前面合并的，要和前面合并退（可能合并特殊退税的，也可能合并正常退税的）。									

            //找出特殊退税点的记录包括FinCheckInvoiceRecordDetailAuxiliaryTab_NewID和金额
            Dictionary<Decimal, Decimal> dicPayTaxPercent2InvoiceYuE = new Dictionary<Decimal, Decimal>();
            Decimal dtTotalNormalPayTaxPointJinE = 0;//正常退税点金额合计
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID = Convert.ToInt32(ds.Tables[0].Rows[i]["FinCheckInvoiceRecordDetailAuxiliaryTab_NewID"].ToString(), 10);
                    Decimal dtPayTaxPercent = Convert.ToDecimal(ds.Tables[0].Rows[i]["PayTaxPercent"].ToString());
                    Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["InvoiceYuE"].ToString());
                    if (dtPayTaxPercent != dtBackTaxPoint)
                    {
                        if (!dicPayTaxPercent2InvoiceYuE.Keys.Contains(dtPayTaxPercent))
                            dicPayTaxPercent2InvoiceYuE.Add(dtPayTaxPercent, dtTemp);
                        else
                        {
                            Decimal dtTemp2 = dicPayTaxPercent2InvoiceYuE[dtPayTaxPercent];
                            dicPayTaxPercent2InvoiceYuE[dtPayTaxPercent] = dtTemp2 + dtTemp;
                        }
                    }
                    else
                    {
                        dtTotalNormalPayTaxPointJinE += dtTemp;
                    }

                }
            }
            //按值由小到大排序
            var result2 = from pair in dicPayTaxPercent2InvoiceYuE orderby pair.Value select pair;

            foreach (KeyValuePair<Decimal, Decimal> pair in result2)
            {
                if (dtPayTaxBenJin == 0)
                    break;

                if (pair.Value <= dtPayTaxBenJin)
                {
                    dtPayTaxBenJin -= pair.Value;
                    al.Add(pair.Value);
                    al.Add(pair.Key);
                }
                else
                {
                    al.Add(dtPayTaxBenJin);
                    al.Add(pair.Key);
                    dtPayTaxBenJin = 0;
                }
            }
            if (dtPayTaxBenJin > 0)
            {
                if (dtTotalNormalPayTaxPointJinE <= dtPayTaxBenJin)
                {
                    dtPayTaxBenJin -= dtTotalNormalPayTaxPointJinE;
                    al.Add(dtTotalNormalPayTaxPointJinE);
                    al.Add(dtBackTaxPoint);
                }
                else
                {
                    al.Add(dtPayTaxBenJin);
                    al.Add(dtBackTaxPoint);
                    dtPayTaxBenJin = 0;
                }
            }


            return al;

        }

       

        //到厂货款计算的结果永远是人民币。
        private void ComputeToFacMoney(ref DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New)
        {
            int nFomularSelect = 0;
            DataSet ds = m_bllFactoryDataTab.GetFactorAInfo("FactoryDataTab.FactoryDataTabID = '"
                + modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID + "'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                nFomularSelect = Convert.ToInt32(ds.Tables[0].Rows[0]["公式选择"].ToString(), 10);
            }

            bool bIsSpecFac = IsSpecFacFun(modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID);

            Decimal dtWaiHuiIncome = 0;
            string strRecvHuiLv = "";
            Decimal dtRecvHuiLv = 0;
            ds = m_bllFinRecvMoneyDetailTab_New.GetList("编号 = '" + modelFinDepRecvAndPayDetailTab_New.RecvBianNo + "'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //dtWaiHuiIncome = (Decimal)ds.Tables[0].Rows[0]["扣费后折算为USD"];
              
                //strRecvHuiLv = ds.Tables[0].Rows[0]["汇率公式"].ToString();
                if (!bIsSpecFac)//美元
                {
                    dtRecvHuiLv = (Decimal)ds.Tables[0].Rows[0]["汇率"];
                    if (dtRecvHuiLv == 0)
                        dtWaiHuiIncome = 0;
                    else
                        dtWaiHuiIncome = (Decimal)ds.Tables[0].Rows[0]["原币金额"] - (Decimal)ds.Tables[0].Rows[0]["费用合计USD"] / (Decimal)ds.Tables[0].Rows[0]["汇率"];
                }
                else//港币
                {
                    dtRecvHuiLv = (Decimal)ds.Tables[0].Rows[0]["港币汇率"];
                    if (dtRecvHuiLv == 0)
                        dtWaiHuiIncome = 0;
                    else
                        dtWaiHuiIncome = (Decimal)ds.Tables[0].Rows[0]["扣费后折算为HKD"];
                }
            }
            switch (modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID)
            {
                case 1://本金
                    {
                        modelFinDepRecvAndPayDetailTab_New.ToFacMoney =
                            modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome * modelFinDepRecvAndPayDetailTab_New.HuiLv;
                        modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi
                            = modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome.ToString() + " * "
                            + modelFinDepRecvAndPayDetailTab_New.HuiLv.ToString();
                        break;
                    }
                case 2://退税
                    {
                        if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_New.BiZhiTabID == 1)
                        {
                            Fin_PayTaxUsd2Usd ptb = new Fin_PayTaxUsd2Usd(m_SQLStringList, m_arrayList);
                            ptb.ProcessRecvInvoice(ref modelFinDepRecvAndPayDetailTab_New, nFomularSelect);
                            ptb.ProcessPayTaxOnRecvMoneyTab(modelFinDepRecvAndPayDetailTab_New);
                            return;
                        }
                        else if(bIsSpecFac && modelFinDepRecvAndPayDetailTab_New.BiZhiTabID == 2)
                        {
                            Fin_PayTaxHkd2Hkd ptb = new Fin_PayTaxHkd2Hkd(m_SQLStringList, m_arrayList);
                            ptb.ProcessRecvInvoice(ref modelFinDepRecvAndPayDetailTab_New, nFomularSelect);
                            ptb.ProcessPayTaxOnRecvMoneyTab(modelFinDepRecvAndPayDetailTab_New);
                            return;
                        }
                        else if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_New.BiZhiTabID == 2)
                        {
                            Fin_PayTaxHkd2Usd ptb = new Fin_PayTaxHkd2Usd(m_SQLStringList, m_arrayList);
                            ptb.ProcessRecvInvoice(ref modelFinDepRecvAndPayDetailTab_New, nFomularSelect);
                            ptb.ProcessPayTaxOnRecvMoneyTab(modelFinDepRecvAndPayDetailTab_New);
                            return;
                        }
                        else if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_New.BiZhiTabID == 5)//BiZhiTabID == 2美元
                        {
                            Fin_PayTaxRmb2Usd ptb = new Fin_PayTaxRmb2Usd(m_SQLStringList, m_arrayList);
                            ptb.ProcessRecvInvoice(ref modelFinDepRecvAndPayDetailTab_New, nFomularSelect);
                            ptb.ProcessPayTaxOnRecvMoneyTab(modelFinDepRecvAndPayDetailTab_New);
                            return;
                        }
                        else if (bIsSpecFac && modelFinDepRecvAndPayDetailTab_New.BiZhiTabID == 5)//BiZhiTabID == 2美元
                        {
                            Fin_PayTaxRmb2Hkd ptb = new Fin_PayTaxRmb2Hkd(m_SQLStringList, m_arrayList);
                            ptb.ProcessRecvInvoice(ref modelFinDepRecvAndPayDetailTab_New, nFomularSelect);
                            ptb.ProcessPayTaxOnRecvMoneyTab(modelFinDepRecvAndPayDetailTab_New);
                            return;
                        }
                        
                        break;
                    }
                case 3://汇差
                    {
                        modelFinDepRecvAndPayDetailTab_New.ToFacMoney =
                            dtWaiHuiIncome * (modelFinDepRecvAndPayDetailTab_New.HuiLv - modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv);
                        modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi =
                            dtWaiHuiIncome.ToString() + " * " + " ( "
                           + modelFinDepRecvAndPayDetailTab_New.HuiLv.ToString()
                            + " - " + modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv.ToString() + " )";
                        break;
                    }
                case 4://价税
                    {
                        if (modelFinDepRecvAndPayDetailTab_New.FactorB == 0)
                        {
                            modelFinDepRecvAndPayDetailTab_New.ToFacMoney = 0;
                            modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi = "0";
                        }
                        else
                        {
                            modelFinDepRecvAndPayDetailTab_New.ToFacMoney =
                            modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome
                            * (modelFinDepRecvAndPayDetailTab_New.HuiLv - modelFinDepRecvAndPayDetailTab_New.FactorA)
                            * (decimal)1.17 / modelFinDepRecvAndPayDetailTab_New.FactorB;

                            modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi
   = modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome.ToString() + " * ( "
   + modelFinDepRecvAndPayDetailTab_New.HuiLv.ToString() + " - " + modelFinDepRecvAndPayDetailTab_New.FactorA.ToString()
   + " ) * 1.17 /" + modelFinDepRecvAndPayDetailTab_New.FactorB.ToString();
                        }
                        break;
                    }
                case 5://约本
                    {
                        modelFinDepRecvAndPayDetailTab_New.ToFacMoney =
                          modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome * modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv;
                        modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi
                           = modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome.ToString() + " * "
                           + modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv.ToString();
                        break;
                    }
                default:
                    {
                        break;
                    }

            }

        }
        

        private bool ModifyGoodsDetail(int nRowIndex)
        {

            try
            {
         
                m_SQLStringList.Clear();
                m_arrayList.Clear();
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
                DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

         
                modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo = CurrentUGR.Cells["编号"].Value.ToString();
                modelFinDepRecvAndPayDetailTab_New.Note = CurrentUGR.Cells["备注"].Value.ToString();
                DateTime dtTemp = (DateTime)CurrentUGR.Cells["收款日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.RecvDate = dtTemp.Date;
                dtTemp = (DateTime)CurrentUGR.Cells["付款日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.PayDate = dtTemp.Date;
                dtTemp = (DateTime)CurrentUGR.Cells["单据日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.DanJuDate = dtTemp.Date;

                dtTemp = (DateTime)CurrentUGR.Cells["收水单日期"].Value;
                modelFinDepRecvAndPayDetailTab_New.RevcShuiDanDate = dtTemp.Date;
                modelFinDepRecvAndPayDetailTab_New.IsPrint = Convert.ToInt32(CurrentUGR.Cells["是否已经打印"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.ContractNoSets = CurrentUGR.Cells["此次付款涉及的合同号集合"].Value.ToString();

                modelFinDepRecvAndPayDetailTab_New.WaiHuiIncome = Convert.ToDecimal(CurrentUGR.Cells["外汇收入"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.ToRMB = Convert.ToDecimal(CurrentUGR.Cells["折合RMB"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.ToFacMoney = Convert.ToDecimal(CurrentUGR.Cells["到厂货款"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.FactorA = Convert.ToDecimal(CurrentUGR.Cells["系数A"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.FactorB = Convert.ToDecimal(CurrentUGR.Cells["系数B"].Value.ToString());
               // modelFinDepRecvAndPayDetailTab_New.PayTaxBenJinGongShi = CurrentUGR.Cells["到厂货款公式"].Value.ToString();
                modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin = Convert.ToDecimal(CurrentUGR.Cells["付税本金"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.GuJiHuiLv = Convert.ToDecimal(CurrentUGR.Cells["估计汇率"].Value.ToString());
                modelFinDepRecvAndPayDetailTab_New.HuiLv = Convert.ToDecimal(CurrentUGR.Cells["当日牌价"].Value.ToString());

                //     modelFinDepRecvAndPayDetailTab_New.BYCompanyTabID = Convert.ToInt32(CurrentUGR.Cells["经营公司"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.BiZhiTabID = Convert.ToInt32(CurrentUGR.Cells["币种"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FactoryDataTabID = Convert.ToInt32(CurrentUGR.Cells["客户"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FinRecvMoneyWayTabID = Convert.ToInt32(CurrentUGR.Cells["收款方式"].Value.ToString(), 10);
                modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID = Convert.ToInt32(CurrentUGR.Cells["摘要"].Value.ToString(), 10);


                m_bllFinDepRecvAndPayDetailTab_New.TransUpdate(modelFinDepRecvAndPayDetailTab_New
                    , m_SQLStringList, m_arrayList);
             
                m_bllSJPackingTab.ExecuteSqlTran(m_SQLStringList, m_arrayList);

                Frm_Main.Log2DB(this.Text, "修改", modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo);
                ShowAllRecord("");
             

                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                if (m_bInsertFlag)
                {
                    ultraGrid1.Rows[e.Row.Index].Cells[2].Activation = Activation.ActivateOnly;
                    m_bInsertFlag = false;
                    if (!AddGoodsDetail(e.Row.Index))
                        e.Cancel = true;



                }
                else//修改
                {

                    ModifyGoodsDetail(e.Row.Index);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private void ultraGrid1_BeforeRowsDeleted(object sender, BeforeRowsDeletedEventArgs e)
        {
            e.DisplayPromptMsg = false;
            if (!m_bInsertFlag)
            {
                int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(ultraGrid1.ActiveRow.Cells[0].Value.ToString(), 10);
                DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinRecvMoneyDetailTab_NewOld = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

                if (modelFinRecvMoneyDetailTab_NewOld == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show("确实要删除该条记录!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    try
                    {

                        m_bllFinDepRecvAndPayDetailTab_New.TransDelete(nSelectFinRecvMoneyDetailTab_NewID, m_SQLStringList, m_arrayList);
                        m_bllSJPackingTab.ExecuteSqlTran(m_SQLStringList, m_arrayList);

                        Frm_Main.Log2DB(this.Text, "删除", modelFinRecvMoneyDetailTab_NewOld.FinDepRecvAndPayDetailTab_NewBianNo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                    }
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                MessageBox.Show("插入未完成，不能删除记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private void ComputeInvoiceAndRecvRemain(int nNewFacTabID, string strRecvNo)
        {
            try
            {
                DataSet dsFac = m_bllFactoryDataTab.GetList("FactoryDataTabID = '" + nNewFacTabID.ToString() + "'");
                if (dsFac.Tables.Count > 0 && dsFac.Tables[0].Rows.Count > 0)
                {
                    this.textBoxFac.Text = dsFac.Tables[0].Rows[0]["工厂简称"].ToString();
                }


                //这里关键收款补充表要搞对
                Decimal dtRecv = GetRecvMoneyRemainNewTongji("FinRecvMoneyAuxiliaryTab_New.IsPayTaxDone = 0 and FinRecvMoneyDetailTab_New.isNotJoinBackTax = 0 and FinRecvMoneyDetailTab_New.FactoryDataTabID = '" + nNewFacTabID.ToString() + "'");

                //DataSet ds = m_bllFinRecvMoneyDetailTab_New.GetList("编号 = '" + strRecvNo + "'");
                //Decimal dtHuiLv = 0;
                //if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                //{
                //    dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["汇率"].ToString());
                //}

                //这里关键审票补充表要搞对
                Decimal dtInvoiceRemain = GetInvoiceRemainTongji("FinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0 and FactoryDataTab.FactoryDataTabID = '" + nNewFacTabID.ToString() + "'");

                //if (dtHuiLv != 0)
                //    dtInvoiceRemain = dtInvoiceRemain / dtHuiLv;
                //else
                //    dtInvoiceRemain = 0;
                //Decimal dtTemp = GetRecvMoneyRemain("FinRecvMoneyAuxiliaryTab_New.IsPayTaxDone = 0 and FinRecvMoneyDetailTab_New.FactoryDataTabID = '" + nNewFacTabID.ToString() + "'");
                this.textBoxRecvMoneyYuE.Text = dtRecv.ToString();
                //dtTemp = GetInvoiceRemain("FinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0 and FactoryDataTab.FactoryDataTabID = '" + nNewFacTabID.ToString() + "'");


                this.textBoxInvoiceYuE.Text = dtInvoiceRemain.ToString();
            }
            catch { }

        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            int iIndex = this.ultraGrid1.ActiveCell.Row.Index;
            if (iIndex < 0)
                return;
            m_nDelIndex = ultraGrid1.ActiveRow.Index;
            try
            {
                UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nDelIndex];
                int nNewFacTabID = Convert.ToInt32(CurrentUGR.Cells["客户"].Value.ToString(), 10);
                string strRecvNo = CurrentUGR.Cells["收款编号"].Value.ToString();
                ComputeInvoiceAndRecvRemain(nNewFacTabID, strRecvNo);
            }
            catch { }

            if (m_bSumStart)
            {
                if (this.ultraGrid1.ActiveCell.Appearance.BackColor.Name == "0")
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.Aqua;
                }
                else
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.FromName("0");
                }
            }

        }

        private void ultraGrid1_AfterRowCancelUpdate(object sender, RowEventArgs e)
        {
            m_bInsertFlag = false;
        }

        private void ultraGrid1_BeforeCellCancelUpdate(object sender, CancelableCellEventArgs e)
        {
            m_bInsertFlag = false;
        }
        private void SetUltraGrid1HidderColumn(bool bSet)
        {
            if (bSet == true)
            {
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = bSet;

                foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "编号" || str == "收款编号" || str == "摘要" || str == "客户" || str == "收款日期"
                        || str == "币种" || str == "外汇收入" || str == "当日牌价"
                        || str == "收款方式" || str == "单据日期" || str == "到厂货款" || str == "不参与退税")
                    {
                        //Color c = column2.CellAppearance.BackColor;
                        column2.CellAppearance.BackColor = m_color;
                      
                    }
                  
                }
            }
            else
            {
                foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "编号" || str == "收款编号" || str == "摘要" || str == "客户" || str == "收款日期"
                        || str == "币种" || str == "外汇收入" || str == "当日牌价"
                        || str == "收款方式" || str == "单据日期" || str == "到厂货款" || str == "不参与退税")
                    {
                        //Color c = column2.CellAppearance.BackColor;
                        column2.CellAppearance.BackColor = Color.Coral;
                      
                    }
                
                }
            }

            ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[2].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[3].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[5].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[9].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[12].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[14].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[15].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[16].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[17].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[18].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[20].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[22].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[23].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[24].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[25].Hidden = bSet;
        }

        private void SetUltraGrid1HidderColumnOther(bool bSet)
        {
            if (bSet == true)
            {
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = bSet;

                foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "编号" || str == "收款编号" || str == "摘要" || str == "客户" || str == "收款日期"
                        || str == "币种" || str == "外汇收入" || str == "当日牌价"
                        || str == "收款方式" || str == "单据日期" || str == "到厂货款" || str == "不参与退税")
                    {
                        //Color c = column2.CellAppearance.BackColor;
                        column2.CellAppearance.BackColor = m_color;

                    }

                }
            }
            else
            {
                foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "编号" || str == "收款编号" || str == "摘要" || str == "客户" || str == "收款日期"
                        || str == "币种" || str == "外汇收入" || str == "当日牌价"
                        || str == "收款方式" || str == "单据日期" || str == "到厂货款" || str == "不参与退税")
                    {
                        //Color c = column2.CellAppearance.BackColor;
                        column2.CellAppearance.BackColor = Color.Coral;

                    }

                }
            }

            ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[2].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[3].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[5].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[9].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[10].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[11].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[12].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[13].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[14].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[15].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[16].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[17].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[18].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[19].Hidden = bSet;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[20].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[22].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[23].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[24].Hidden = bSet;
            ultraGrid1.DisplayLayout.Bands[0].Columns[25].Hidden = bSet;
        }
        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;
            //m_dt.Clear();
            //m_dt = (DataTable)ultraGrid1.DataSource;
            m_bIsExportAllColumn = false;
            m_ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }
                    SetUltraGrid1HidderColumn(true);
                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                    SetUltraGrid1HidderColumn(false);
                }
            }
            //m_dt.Clear();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            if (!m_bInsertFlag)
            {
                UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();
                //  row.Cells[2] = DateTime.Parse("1900-01-01");
            }
        }

        private void DeleteBackTaxRecord(int nSelectFinRecvMoneyDetailTab_NewID)
        {
            DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_New = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);


            if ((modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID == 2
                || modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID == 4)
                && modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin > 0)
            {

                string strPayNo = modelFinDepRecvAndPayDetailTab_New.FinDepRecvAndPayDetailTab_NewBianNo;
                DataSet ds = m_bllFinRecvMoneyAuxiliaryTab_New.GetList("PayTaxBianHao = '" + strPayNo + "'");
                //同一个退税编号可能涉及很多合同号
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    int nAppendNumIndex = 0;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        int nFinRecvMoneyAuxiliaryTab_NewID = Convert.ToInt32(ds.Tables[0].Rows[i]["FinRecvMoneyAuxiliaryTab_NewID"].ToString(), 10);
                        int nFinRecvMoneyDetailTab_NewID = Convert.ToInt32(ds.Tables[0].Rows[i]["FinRecvMoneyDetailTab_NewID"].ToString(), 10);


                        DGBY.Model.FinRecvMoneyAuxiliaryTab_New modelFinRecvMoneyAuxiliaryTab_New
                            = m_bllFinRecvMoneyAuxiliaryTab_New.GetModel(nFinRecvMoneyAuxiliaryTab_NewID);

                        if (modelFinRecvMoneyAuxiliaryTab_New.IsPayTaxDone > 0)
                        {
                            //先把最小序号的已付税标志置为0
                            modelFinRecvMoneyAuxiliaryTab_New.IsPayTaxDone = 0;
                            DataSet dsTempRecvOO = m_bllFinRecvMoneyAuxiliaryTab_New.GetListMaxSeq("FinRecvMoneyDetailTab_NewID = '"
    + nFinRecvMoneyDetailTab_NewID.ToString() + "' and IsPayTaxDone > 0");
                            if (dsTempRecvOO.Tables.Count > 0 && dsTempRecvOO.Tables[0].Rows.Count > 0)
                            {
                                int nMaxSubSeqNo = (int)dsTempRecvOO.Tables[0].Rows[0]["maxSubSeqNo"];
                                if (modelFinRecvMoneyAuxiliaryTab_New.PayTaxMoneyValue > modelFinRecvMoneyAuxiliaryTab_New.PayedTaxMoneyValue
                                   && modelFinRecvMoneyAuxiliaryTab_New.SubSeqNo < nMaxSubSeqNo)
                                    modelFinRecvMoneyAuxiliaryTab_New.PayTaxMoneyValue = modelFinRecvMoneyAuxiliaryTab_New.PayedTaxMoneyValue;
                            }

                            modelFinRecvMoneyAuxiliaryTab_New.PayedTaxMoneyValue = 0;
                            modelFinRecvMoneyAuxiliaryTab_New.PayTaxBianHao = "";
                            m_bllFinRecvMoneyAuxiliaryTab_New.TransUpdate(modelFinRecvMoneyAuxiliaryTab_New
                               , m_SQLStringList, m_arrayList, i);

                          
                            if (modelFinRecvMoneyAuxiliaryTab_New.SubSeqNo == 0)
                            {
                                DGBY.Model.FinRecvMoneyDetailTab_New modelFinRecvMoneyDetailTab_New
= m_bllFinRecvMoneyDetailTab_New.GetModel(nFinRecvMoneyDetailTab_NewID);
                                modelFinRecvMoneyDetailTab_New.IsPayTaxDone = 0;
                                m_bllFinRecvMoneyDetailTab_New.TransUpdate(modelFinRecvMoneyDetailTab_New
                                    , m_SQLStringList, m_arrayList, i);

                            }

                            List<int> lstDelRecvAuxiliary = new List<int>();
                            lstDelRecvAuxiliary.Add(nFinRecvMoneyAuxiliaryTab_NewID);
                            //获取收款表id的所有补充表id集合。
                            DataSet dsTempRecv = m_bllFinRecvMoneyAuxiliaryTab_New.GetList("FinRecvMoneyDetailTab_NewID = '"
                                + nFinRecvMoneyDetailTab_NewID.ToString() + "'");

                            if (dsTempRecv.Tables.Count > 0 && dsTempRecv.Tables[0].Rows.Count > 0)
                            {
                                bool bFatherHadBackTax = false;//子序号为0的节点已经退税
                                for (int k = 0; k < dsTempRecv.Tables[0].Rows.Count; k++)
                                {
                                    nAppendNumIndex++;
                                    int nSubFinRecvMoneyAuxiliaryTab_NewID =
                                        Convert.ToInt32(dsTempRecv.Tables[0].Rows[k]["FinRecvMoneyAuxiliaryTab_NewID"].ToString(), 10);
                                    DGBY.Model.FinRecvMoneyAuxiliaryTab_New modelFinRecvMoneyAuxiliaryTab_New2
= m_bllFinRecvMoneyAuxiliaryTab_New.GetModel(nSubFinRecvMoneyAuxiliaryTab_NewID);

                                    //k==0的情况，当父节点已经退了税（IsPayTaxDone == 0）
                                    //lstDelFatherAuxiliary.Contains(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID)的情况，
                                    //
                                    if (k == 0
                                        //|| lstDelFatherAuxiliary.Contains(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID)
                                        )
                                    {
                                        if (modelFinRecvMoneyAuxiliaryTab_New2.IsPayTaxDone == 0)
                                            bFatherHadBackTax = true;
                                    }
                                    //如果子序号大于0，且已经退税或者（本次要退税且父节点已经退过税）
                                    if (modelFinRecvMoneyAuxiliaryTab_New2.SubSeqNo > 0
                                        && modelFinRecvMoneyAuxiliaryTab_New2.PayedTaxMoneyValue == 0
                                        || (lstDelRecvAuxiliary.Contains(nSubFinRecvMoneyAuxiliaryTab_NewID)
                                        && bFatherHadBackTax)
                                        )
                                    {
                                        m_bllFinRecvMoneyAuxiliaryTab_New.TransDelete(nSubFinRecvMoneyAuxiliaryTab_NewID
                                            , m_SQLStringList, m_arrayList, nAppendNumIndex);
                                    }
                                }
                            }

                        }


                    }
                }

                ds = m_bllInvoiceAuxiliary_New.GetList("PayTaxBianHao = '" + strPayNo + "'");
                //同一个退税编号可能涉及很多合同号，审票记录
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    int nAppendNumIndex = 0;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        int nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID = Convert.ToInt32(ds.Tables[0].Rows[i]["FinCheckInvoiceRecordDetailAuxiliaryTab_NewID"].ToString(), 10);
                        int nFinCheckInvoiceRecordDetailTab_NewID = Convert.ToInt32(ds.Tables[0].Rows[i]["FinCheckInvoiceRecordDetailTab_NewID"].ToString(), 10);
                        DGBY.Model.FinCheckInvoiceRecordDetailAuxiliaryTab_New modelFinCheckInvoiceRecordDetailAuxiliaryTab_New
                            = m_bllInvoiceAuxiliary_New.GetModel(nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID);
                        //if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.SubSeqNo == 0)
                        //    m_bllInvoiceAuxiliary_New.TransDelete(nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID
                        //        , m_SQLStringList, m_arrayList, i);
                        //else 
                        if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone > 0)
                        {
                            modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0;

                            DataSet dsTempInvoiceOO = m_bllInvoiceAuxiliary_New.GetListMaxSeq("FinCheckInvoiceRecordDetailTab_NewID = '"
                             + nFinCheckInvoiceRecordDetailTab_NewID.ToString() + "' and IsPayTaxDone > 0");
                            if (dsTempInvoiceOO.Tables.Count > 0 && dsTempInvoiceOO.Tables[0].Rows.Count > 0)
                            {
                                int nMaxSubSeqNo = (int)dsTempInvoiceOO.Tables[0].Rows[0]["maxSubSeqNo"];
                                if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayTaxMoneyValue > modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayedTaxMoneyValue
                                    && modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.SubSeqNo < nMaxSubSeqNo)
                                    modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayTaxMoneyValue = modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayedTaxMoneyValue;
                            }
                            

                            modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayedTaxMoneyValue = 0;
                        
                            modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.PayTaxBianHao = "";
                            m_bllInvoiceAuxiliary_New.TransUpdate(modelFinCheckInvoiceRecordDetailAuxiliaryTab_New
                                , m_SQLStringList, m_arrayList, i);

                            //本次计划退税（PayedTaxMoneyValue变为0）且子序号为0的补充表的集合。
                            //List<int> lstDelFatherAuxiliary = new List<int>();
                            if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New.SubSeqNo == 0)
                            {
                                DGBY.Model.FinCheckInvoiceRecordDetailTab_New modelFinCheckInvoiceRecordDetailTab_New
= m_bllFinCheckInvoiceRecordDetailTab_New.GetModel(nFinCheckInvoiceRecordDetailTab_NewID);
                                modelFinCheckInvoiceRecordDetailTab_New.IsPayTaxDone = 0;
                                m_bllFinCheckInvoiceRecordDetailTab_New.TransUpdate(modelFinCheckInvoiceRecordDetailTab_New
                                    , m_SQLStringList, m_arrayList, i);

                                //lstDelFatherAuxiliary.Add(nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID);

                            }
                            //本次计划退税（PayedTaxMoneyValue变为0）的补充表的集合。
                            List<int> lstDelAuxiliary = new List<int>();
                            lstDelAuxiliary.Add(nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID);
                            DataSet dsTempInvoice = m_bllInvoiceAuxiliary_New.GetList("FinCheckInvoiceRecordDetailTab_NewID = '"
                                + nFinCheckInvoiceRecordDetailTab_NewID.ToString() + "'");
                            if (dsTempInvoice.Tables.Count > 0 && dsTempInvoice.Tables[0].Rows.Count > 0)
                            {
                                bool bFatherHadBackTax = false;//子序号为0的节点已经退税
                                for (int k = 0; k < dsTempInvoice.Tables[0].Rows.Count; k++)
                                {
                                    nAppendNumIndex++;
                                    int nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID =
                                        Convert.ToInt32(dsTempInvoice.Tables[0].Rows[k]["FinCheckInvoiceRecordDetailAuxiliaryTab_NewID"].ToString(), 10);
                                    DGBY.Model.FinCheckInvoiceRecordDetailAuxiliaryTab_New modelFinCheckInvoiceRecordDetailAuxiliaryTab_New2
= m_bllInvoiceAuxiliary_New.GetModel(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID);

                                    //k==0的情况，当父节点已经退了税（IsPayTaxDone == 0）
                                    //lstDelFatherAuxiliary.Contains(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID)的情况，
                                    //
                                    if (k == 0
                                        //|| lstDelFatherAuxiliary.Contains(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID)
                                        )
                                    {
                                        if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New2.IsPayTaxDone == 0)
                                            bFatherHadBackTax = true;
                                    }
                                    //如果子序号大于0，且已经退税或者（本次要退税且父节点已经退过税）
                                    if (modelFinCheckInvoiceRecordDetailAuxiliaryTab_New2.SubSeqNo > 0
                                        && modelFinCheckInvoiceRecordDetailAuxiliaryTab_New2.PayedTaxMoneyValue == 0
                                        || (lstDelAuxiliary.Contains(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID)
                                        && bFatherHadBackTax)
                                        )
                                    {
                                        m_bllInvoiceAuxiliary_New.TransDelete(nSubFinCheckInvoiceRecordDetailAuxiliaryTab_NewID
                                            , m_SQLStringList, m_arrayList, nAppendNumIndex);
                                    }
                                }
                            }

                        }


                        //DataSet dsInvoice = m_bllFinCheckInvoiceRecordDetailTab_New.GetList("FinCheckInvoiceRecordDetailTab_NewID = '" + nFinCheckInvoiceRecordDetailAuxiliaryTab_NewID.ToString() + "'");
                        //if (dsInvoice.Tables.Count > 0 && dsInvoice.Tables[0].Rows.Count > 0)
                        //{
                        //    int nFinCheckInvoiceRecordDetailTab_NewID = Convert.ToInt32(dsInvoice.Tables[0].Rows[0]["FinCheckInvoiceRecordDetailTab_NewID"].ToString(), 10);

                        //}
                    }
                }
                //MessageBox.Show("已退税，不能删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //m_bCanModify = false;
                //return;
            }
        }


        private void toolStripMenuItemDel_Click(object sender, EventArgs e)
        {
            int nIndex = m_nDelIndex;
            if (m_nDelIndex < 0)
                return;

            if (backgroundWorker1.IsBusy)
                return;
            m_nDelbackgroundIndex = m_nDelIndex;

            progressBarBackup.Visible = true;
            this.labelProcess.Visible = true;
            progressBarBackup.Maximum = 100;
            progressBarBackup.Value = 0;
            backgroundWorker1.RunWorkerAsync();
        }
        private void ComputeRemainValue()
        {
            DataSet ds = m_bllFactoryDataTab.GetFinList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxOrderCustom.DataSource = ds.Tables[0];

                this.comboBoxOrderCustom.ValueMember = "FactoryDataTabID";
                this.comboBoxOrderCustom.DisplayMember = "工厂简称";
                this.comboBoxOrderCustom.AutoCompleteSource = AutoCompleteSource.ListItems;
                this.comboBoxOrderCustom.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                this.comboBoxOrderCustom.SelectedIndex = 0;
            }
            else
            {
                this.comboBoxOrderCustom.Enabled = false;
            }
        }
        private bool IsSpecFacFun(int nFacID)
        {
            
      
            DataSet dsFac = m_bllFactoryDataTab.GetFinSpecFacInfo("FactoryDataTab.FactoryDataTabid = '" + nFacID.ToString() + "'");
            bool bIsHkFac = (bool)dsFac.Tables[0].Rows[0]["是否港币出货工厂"];

            return bIsHkFac;
          
        
        }
        private void InitColumnWidth()
        {
            int nWidth = 20;
            ultraGrid1.DisplayLayout.Bands[0].Columns["不参与退税"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["编号"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收款编号"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["客户"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["经营单位"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["摘要"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收款日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["币种"].Width = 40;
            ultraGrid1.DisplayLayout.Bands[0].Columns["外汇收入公式"].Width = 240;
            ultraGrid1.DisplayLayout.Bands[0].Columns["外汇收入"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["当日牌价"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["估计汇率"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收款方式"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["折合RMB"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["付汇差本金公式"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["付税本金"].Width = 70;
            ultraGrid1.DisplayLayout.Bands[0].Columns["系数A"].Width = 70;
            ultraGrid1.DisplayLayout.Bands[0].Columns["系数B"].Width = 70;
            ultraGrid1.DisplayLayout.Bands[0].Columns["付款日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["到厂货款公式"].Width = nWidth + 500;  
            ultraGrid1.DisplayLayout.Bands[0].Columns["付汇差本金公式"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["到厂货款"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["单据日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["此次付款涉及的合同号集合"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否已经打印"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收水单日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["备注"].Width = 100;    
        }
        private void Frm_PayAndRecvTab_Load(object sender, EventArgs e)
        {
            ComputeRemainValue();
            ClassUltraGridCommonSet.InitUltraWinGridSetting(this.ultraGrid1);
            int nMaxID = m_bllFinDepRecvAndPayDetailTab_New.GetMaxId() - 1;
            ShowAllRecord("FinDepRecvAndPayDetailTab_NewID = '" + nMaxID.ToString() + "'");
        }
        //这里存在币制的问题
        private void comboBoxOrderCustom_SelectedIndexChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    string str = this.comboBoxOrderCustom.SelectedValue.ToString();
            //    int nID = Convert.ToInt32(str, 10);

            //    Decimal dtTemp = GetRecvMoneyRemain("FinRecvMoneyAuxiliaryTab_New.IsPayTaxDone = 0 and FinRecvMoneyDetailTab_New.FactoryDataTabID = '" + nID.ToString() + "'");
            //    this.textBoxRecvMoneyYuE.Text = dtTemp.ToString();
            //    dtTemp = GetInvoiceRemain("FinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0 and FactoryDataTab.FactoryDataTabID = '" + nID.ToString() + "'");


            //    this.textBoxInvoiceYuE.Text = dtTemp.ToString();
            //}
            //catch { }

        }

        private void buttonRefreshValue_Click(object sender, EventArgs e)
        {
            ComputeRemainValue();
        }
      


        

      
        private void ultraGrid1_AfterCellUpdate(object sender, CellEventArgs e)
        {
           
        }
        private void SetFormula(Control control, string formula)
        {
            // To acces extender the CalcManager extender properties, call 
            // the first get the GetCalcSettings method.
            CalcSettings objCalcSettings = null;
            objCalcSettings = this.ultraCalcManager1.GetCalcSettings(control);

            // Set the formula. 
            objCalcSettings.Formula = formula;
        }
        private void textBoxPayTaxFormula_TextChanged(object sender, EventArgs e)
        {
            SetFormula(this.textBoxPayTaxValue, this.textBoxPayTaxFormula.Text);
        }

        private void textBoxPayTaxValue_TextChanged(object sender, EventArgs e)
        {
            UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nSelectRowIndex];
            CurrentUGR.Cells["付税本金"].Value = Convert.ToDecimal(this.textBoxPayTaxValue.Text);
            ModifyGoodsDetail(m_nSelectRowIndex);
        }

        private void buttonExportZhiPiao_Click(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                MessageBox.Show("没有要批量打印的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            for (int i = 0; i < ugr.Length; i++)
            {
                DataTable dt1 = new DataTable();
                int nID = Convert.ToInt32(ugr[i].Cells["客户"].Value.ToString(), 10);

                Decimal dtTemp = (Decimal)Convert.ToDecimal(ugr[i].Cells["到厂货款"].Value.ToString());
                DataSet ds = m_bllFactoryDataTab.GetListEx("FactoryDataTabID = '" + nID.ToString() + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    dt1 = ds.Tables[0];
                }
                string templetFile = templetFilePath + "银行转账支票凭证.xlt";
                string outFile = "";

                ExcelBase eB = new ExcelBase(templetFile, outFile);
                ds = bllTaoDaPrinterNameTab.GetList("");
                string strPrinterNameTemp = "";
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    strPrinterNameTemp = ds.Tables[0].Rows[0]["TaoDaPrinterName"].ToString();
                }
                try
                {
                    //eB.BankZhiPiao_DataTableToExcel(dt1, dtTemp);
                    eB.BankZhiPiao_DataTablePrint(dt1, dtTemp, strPrinterNameTemp, Frm_Main.m_strLoginUser);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                try
                {
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(ugr[i].Cells[0].Value.ToString(), 10);
                    DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_NewTemp
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    modelFinDepRecvAndPayDetailTab_NewTemp.IsPrint = 1;
                    m_bllFinDepRecvAndPayDetailTab_New.Update(modelFinDepRecvAndPayDetailTab_NewTemp);
                }
                catch (System.Exception ex)
                {

                }
                eB.Close();
            }


            //DataTable dt1 = (DataTable)this.ultraGrid1.DataSource;
            //if (dt1 != null)
            //{
            //    if (dt1.Rows.Count > 0)
            //    {
            //        Decimal dtTemp = (Decimal)Convert.ToDecimal(dt1.Rows[0]["到厂货款"].ToString());
            //        int nID = Convert.ToInt32(dt1.Rows[0]["客户"].ToString(), 10);
            //        DataSet ds = m_bllFactoryDataTab.GetListEx("FactoryDataTabID = '" + nID.ToString() + "'");
            //        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //        {
            //            dt1 = ds.Tables[0];
            //        }

            //        SaveFileDialog sfd = new SaveFileDialog();
            //        sfd.Filter = "Excel文件(*.xls)|*.xls";
            //        string outFile = "";

            //        if (sfd.ShowDialog() == DialogResult.OK)
            //        {
            //            outFile = sfd.FileName;
            //        }
            //        else
            //        {
            //            return;
            //        }

            //        string templetFile = templetFilePath + "银行转账支票凭证.xlt";

            //        ExcelBase eB = new ExcelBase(templetFile, outFile);
            //        ds = bllTaoDaPrinterNameTab.GetList("");
            //        string strPrinterNameTemp = "";
            //        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //        {
            //            strPrinterNameTemp = ds.Tables[0].Rows[0]["TaoDaPrinterName"].ToString();
            //        }
            //        try
            //        {
            //            //eB.BankZhiPiao_DataTableToExcel(dt1, dtTemp);
            //            eB.BankZhiPiao_DataTablePrint(dt1, dtTemp, strPrinterNameTemp);
            //        }
            //        catch (System.Exception ex)
            //        {
            //            MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        }

            //        eB.Close();
                
            
            //else
            //{
            //    MessageBox.Show("付款记录不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
        }

        private Decimal Invoice2RecvMoney(string strRecvBizhi, Decimal dtInvoice, string strInvoiceBizhi)
        {
            Decimal dtConvertDtRecv = 0;



            return dtConvertDtRecv;
        }
        //退税大方面分2种情况，每种情况都有一定的复杂点
        //1.本次收款 > 全部审票，审票全退完，是简单之处，复杂点是收款不能一次退完。
        //2.本次收款 < 全部审票，收款全退完，是简单之处，复杂点是审票要按顺序退。相对来说2更简单些。 
        private void 复制增加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!m_bInsertFlag)
                {



                    UltraGridRow CurrentUGRFrom;
                    CurrentUGRFrom = ultraGrid1.Rows[m_nDelIndex];
                    bool bIsNotJoinBackTax = Convert.ToBoolean(CurrentUGRFrom.Cells["不参与退税"].Value.ToString());
                    if(bIsNotJoinBackTax == true)
                    {
                        MessageBox.Show("该笔收款被设定为不参与退税，不能复制增加退税", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;

                    }

                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGRFrom.Cells[0].Value.ToString(), 10);
                    DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_NewTemp
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    if (modelFinDepRecvAndPayDetailTab_NewTemp.FinAbstractTabID != 1
                        && modelFinDepRecvAndPayDetailTab_NewTemp.FinAbstractTabID != 5)
                    {
                        MessageBox.Show("复制源不是付款本金或付款约定本金，不能复制增加退税", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;

                    }
                
                    Decimal dtRecv = GetRecvMoneyRemainNew("RecvBianNo = '" + modelFinDepRecvAndPayDetailTab_NewTemp.RecvBianNo +
"' and FinDepRecvAndPayDetailTab_New.FactoryDataTabID = '" + modelFinDepRecvAndPayDetailTab_NewTemp.FactoryDataTabID.ToString() + "'");

                    //DataSet ds = m_bllFinRecvMoneyDetailTab_New.GetList("z1.不参与退税 = 0 and 编号 = '" + modelFinDepRecvAndPayDetailTab_NewTemp.RecvBianNo + "'");
                    //Decimal dtHuiLv = 0;
                    //if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    //{
                    //    if(bIsSpecFac)
                    //        dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["港币汇率"].ToString());
                    //    else
                    //        dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["汇率"].ToString());
                    //}

                    Decimal dtInvoice2RecvFactor = 0;

                    DataSet ds;
                    bool bIsSpecFac = IsSpecFacFun(modelFinDepRecvAndPayDetailTab_NewTemp.FactoryDataTabID);
                    if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_NewTemp.BiZhiTabID == 1)//BiZhiTabID == 1 美元
                    {
                        dtInvoice2RecvFactor = 1;
                    }
                    else if (bIsSpecFac && modelFinDepRecvAndPayDetailTab_NewTemp.BiZhiTabID == 2)//BiZhiTabID == 2港币
                    {
                        dtInvoice2RecvFactor = 1;
                    }
                    else if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_NewTemp.BiZhiTabID == 2)//BiZhiTabID == 2美元
                    {
                        ds = m_bllFinRecvMoneyDetailTab_New.GetList("z1.不参与退税 = 0 and 编号 = '" + modelFinDepRecvAndPayDetailTab_NewTemp.RecvBianNo + "'");
                        Decimal dtHuiLv = 0;
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["汇率"].ToString());
                        }
                        dtInvoice2RecvFactor = dtHuiLv;//港币兑美元汇率0.128左右
                    }
                    else if (!bIsSpecFac && modelFinDepRecvAndPayDetailTab_NewTemp.BiZhiTabID == 5)//BiZhiTabID == 2美元
                    {
                        ds = m_bllFinRecvMoneyDetailTab_New.GetList("z1.不参与退税 = 0 and 编号 = '" + modelFinDepRecvAndPayDetailTab_NewTemp.RecvBianNo + "'");
                        Decimal dtHuiLv = 0;
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["汇率"].ToString());
                        }
                        dtInvoice2RecvFactor = dtHuiLv;//港币兑美元汇率0.128左右
                    }
                    else if (bIsSpecFac && modelFinDepRecvAndPayDetailTab_NewTemp.BiZhiTabID == 5)//BiZhiTabID == 2美元
                    {
                        ds = m_bllFinRecvMoneyDetailTab_New.GetList("z1.不参与退税 = 0 and 编号 = '" + modelFinDepRecvAndPayDetailTab_NewTemp.RecvBianNo + "'");
                        Decimal dtHuiLv = 0;
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            dtHuiLv = Convert.ToDecimal(ds.Tables[0].Rows[0]["港币汇率"].ToString());
                            if (dtHuiLv == 0)
                            {
                                MessageBox.Show("收款的港币汇率不能为0!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            dtHuiLv = 1 / dtHuiLv;
                        }
                        dtInvoice2RecvFactor = dtHuiLv;//港币兑美元汇率0.128左右
                    }
                    else
                    {
                        MessageBox.Show("目前不支持该种收款审票币制组合的退税!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    Decimal dtInvoiceRemain = GetInvoiceRemain("FinCheckInvoiceRecordDetailAuxiliaryTab_New.IsPayTaxDone = 0 and FactoryDataTab.FactoryDataTabID = '" + modelFinDepRecvAndPayDetailTab_NewTemp.FactoryDataTabID.ToString() + "'");

                    //if (dtHuiLv != 0)
                    //    dtInvoiceRemain = dtInvoiceRemain / dtHuiLv;//按照本次收款汇率折算成收款币制
                    //else
                    //    dtInvoiceRemain = 0;
                    dtInvoiceRemain = dtInvoiceRemain / dtInvoice2RecvFactor;
                    

                    if(dtInvoiceRemain <= 0)
                    {
                        MessageBox.Show("发票余额为0，不能复制增加退税", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (dtRecv <= 0)
                    {
                        MessageBox.Show("收款余额为0，不能复制增加退税", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    int nFormulaSelector = 0;
                    Decimal dtFactorA = 0;
                    DataSet dsInfo = m_bllFactoryDataTab.GetFactorAInfo("FactoryDataTab.FactoryDataTabID = '"
                        + modelFinDepRecvAndPayDetailTab_NewTemp.FactoryDataTabID.ToString() + "'");
                    if (dsInfo.Tables.Count > 0 && dsInfo.Tables[0].Rows.Count > 0)
                    {
                        dtFactorA = Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["系数A"].ToString());
                        nFormulaSelector = Convert.ToInt32(dsInfo.Tables[0].Rows[0]["公式选择"].ToString(), 10);

                    }


                    Decimal dtBackTaxPoint = 0;
                    dsInfo = m_bllFactoryGoodsTab.GetGoodsBandInfo("FactoryDataTab.FactoryDataTabID = '"
                        + modelFinDepRecvAndPayDetailTab_NewTemp.FactoryDataTabID.ToString() + "'");
                    if (dsInfo.Tables.Count > 0 && dsInfo.Tables[0].Rows.Count > 0)
                    {
                        //dtBackTaxPoint = 1.17M - Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["退税点"].ToString());
                        dtBackTaxPoint = Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["设百分比"].ToString());
                    }
             

                    Decimal dtPayTaxBenjin = 0;
                    if (dtRecv > dtInvoiceRemain)
                        dtPayTaxBenjin = dtInvoiceRemain;
                    else
                        dtPayTaxBenjin = dtRecv;

                    m_modelFinDepRecvAndPayDetailTab_New
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    //约定本金，拷贝汇率
                    if (modelFinDepRecvAndPayDetailTab_NewTemp.FinAbstractTabID == 5)
                    {
                        ds = m_bllFinRecvMoneyDetailTab_New.GetList("编号 = '" + m_modelFinDepRecvAndPayDetailTab_New.RecvBianNo + "'");
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            m_modelFinDepRecvAndPayDetailTab_New.HuiLv = (Decimal)ds.Tables[0].Rows[0]["RMB汇率"];
                        }

                    }
    

                    m_modelFinDepRecvAndPayDetailTab_New.FactorA = dtFactorA;
                    m_modelFinDepRecvAndPayDetailTab_New.FactorB = dtBackTaxPoint;
                  
                    m_modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID = 2;
                    m_modelFinDepRecvAndPayDetailTab_New.PayTaxBenJin = dtPayTaxBenjin;
                    m_bCopyInsertFlag = true;
                    UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString()+"没有选择记录，无法复制！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void 复制增加汇差ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!m_bInsertFlag)
                {
                    UltraGridRow CurrentUGRFrom;
                    CurrentUGRFrom = ultraGrid1.Rows[m_nDelIndex];
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGRFrom.Cells[0].Value.ToString(), 10);
                    DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_NewTemp
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    if (modelFinDepRecvAndPayDetailTab_NewTemp.FinAbstractTabID != 5)
                    {
                        MessageBox.Show("复制源不是付款约定本金，不能复制增加汇差", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;

                    }

                    m_modelFinDepRecvAndPayDetailTab_New
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

                    m_modelFinDepRecvAndPayDetailTab_New.FinAbstractTabID = 3;
                    DataSet ds = m_bllFinRecvMoneyDetailTab_New.GetList("编号 = '" + m_modelFinDepRecvAndPayDetailTab_New.RecvBianNo+"'");
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        m_modelFinDepRecvAndPayDetailTab_New.HuiLv = (Decimal)ds.Tables[0].Rows[0]["RMB汇率"];
                    }
                    
                    
                    m_bCopyInsertFlag = true;
                    UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();


                    //  row.Cells[2] = DateTime.Parse("1900-01-01");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("没有选择记录，无法复制！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void ultraGrid1_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void ultraGrid1_Click(object sender, EventArgs e)
        {

        }

        private void 导出银行转账支票凭证ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt1 = new DataTable();
                UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nDelIndex];
                int nID = Convert.ToInt32(CurrentUGR.Cells["客户"].Value.ToString(), 10);
                Decimal dtTemp = (Decimal)Convert.ToDecimal(CurrentUGR.Cells["到厂货款"].Value.ToString());

                DataSet ds = m_bllFactoryDataTab.GetListEx("FactoryDataTabID = '" + nID.ToString() + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    dt1 = ds.Tables[0];
                }

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel文件(*.xls)|*.xls";
                string outFile = "";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    outFile = sfd.FileName;
                }
                else
                {
                    return;
                }

                string templetFile = templetFilePath + "银行转账支票凭证.xlt";

                ExcelBase eB = new ExcelBase(templetFile, outFile);
                ds = bllTaoDaPrinterNameTab.GetList("");
                string strPrinterNameTemp = "";
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    strPrinterNameTemp = ds.Tables[0].Rows[0]["TaoDaPrinterName"].ToString();
                }
                eB.BankZhiPiao_DataTableToExcel(dt1, dtTemp, Frm_Main.m_strLoginUser);
                //eB.BankZhiPiao_DataTablePrint(dt1, dtTemp, strPrinterNameTemp);
                try
                {
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
                    DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_NewTemp
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    modelFinDepRecvAndPayDetailTab_NewTemp.IsPrint = 1;
                    m_bllFinDepRecvAndPayDetailTab_New.Update(modelFinDepRecvAndPayDetailTab_NewTemp);
                }
                catch (System.Exception ex)
                {

                }
                eB.Close();
            }
            catch (Exception ex)
            { 
            }
        }

        private void buttonSumStart_Click(object sender, EventArgs e)
        {
            m_bSumStart = true;
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            for (int i = 0; i < ugr.Length; i++)
            {
                for (int j = 0; j < ugr[i].Cells.Count; j++)
                {
                    if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                    {
                        ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                    }
                }
            }
        }

        private void buttonSumStop_Click(object sender, EventArgs e)
        {
            try
            {
                Decimal dtTotal = 0;
                Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                for (int i = 0; i < ugr.Length; i++)
                {
                    for (int j = 0; j < ugr[i].Cells.Count; j++)
                    {
                        if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                        {
                            Decimal dtTemp = Convert.ToDecimal(ugr[i].Cells[j].Value.ToString());
                            dtTotal += dtTemp;
                            //ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                        }
                    }
                }

                this.textBoxTotal.Text = dtTotal.ToString();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void ultraGrid1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                UltraGrid grid = (UltraGrid)sender;
                UIElement element = grid.DisplayLayout.UIElement.LastElementEntered;
                if (element == null)
                    return;
                Infragistics.Win.UltraWinGrid.ColumnHeader columnHeader = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader)) as Infragistics.Win.UltraWinGrid.ColumnHeader;
                if (columnHeader != null)
                {
                    string str = columnHeader.Caption;

                    Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                    if (ugr.Length <= 0)
                    {
                        return;
                    }
                    Decimal dtTemp = 0;
                    for (int i = 0; i < ugr.Length; i++)
                    {
                        if (ugr[i].Cells[str].Value is Decimal || ugr[i].Cells[str].Value is int)
                        {
                            string strTemp = ugr[i].Cells[str].Value.ToString();
                            if (strTemp != "")
                                dtTemp += Convert.ToDecimal(ugr[i].Cells[str].Value.ToString());
                        }
                    }
                    this.textBoxTotal.Text = dtTemp.ToString();




                }
                else
                {
                    // Set the grid's tooltip to null. 
                    //  Debug.WriteLine("null");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;
            int iRdex = e.CurrentRowIndex;
            int iCdex = e.CurrentColumnIndex;
            //e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].CellFormat.FillPatternForegroundColor = Color.FromArgb(0, 0, 0); 
            // string strColumnName = e.GridColumn;
            if (e.GridColumn.Key == "外汇收入" || e.GridColumn.Key == "到厂货款")
            //if (e.GridColumn.Key == "外汇收入" )
            {
                //m_ugr[iRdex-1].Cells[e.GridColumn.Key + "公式"].Value.ToString()
                if (!m_bIsExportAllColumn)
                {
                    try
                    {
                        e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].ApplyFormula(m_ugr[iRdex - 1].Cells[e.GridColumn.Key + "公式"].Value.ToString() == "" ? "=0" : "=" + m_ugr[iRdex - 1].Cells[e.GridColumn.Key + "公式"].Value.ToString());

                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }
     
            
       
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                MessageBox.Show("没有要批量打印的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            Decimal dtTotalTemp = 0;
            for (int i = 0; i < ugr.Length; i++)
            {
                DataTable dt1 = new DataTable();
                int nID = Convert.ToInt32(ugr[i].Cells["客户"].Value.ToString(), 10);

                dtTotalTemp += (Decimal)Convert.ToDecimal(ugr[i].Cells["到厂货款"].Value.ToString());
                DataSet ds = m_bllFactoryDataTab.GetListEx("FactoryDataTabID = '" + nID.ToString() + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    dt1 = ds.Tables[0];
                }

                if (i == ugr.Length - 1)
                {
                    string templetFile = templetFilePath + "银行转账支票凭证.xlt";
                    string outFile = "";

                    ExcelBase eB = new ExcelBase(templetFile, outFile);
                    ds = bllTaoDaPrinterNameTab.GetList("");
                    string strPrinterNameTemp = "";
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        strPrinterNameTemp = ds.Tables[0].Rows[0]["TaoDaPrinterName"].ToString();
                    }
                    try
                    {
                        //eB.BankZhiPiao_DataTableToExcel(dt1, dtTemp);
                        eB.BankZhiPiao_DataTablePrint(dt1, dtTotalTemp, strPrinterNameTemp, Frm_Main.m_strLoginUser);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    eB.Close();
                }
                try
                {
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(ugr[i].Cells[0].Value.ToString(), 10);
                    DGBY.Model.FinDepRecvAndPayDetailTab_New modelFinDepRecvAndPayDetailTab_NewTemp
                        = m_bllFinDepRecvAndPayDetailTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                    modelFinDepRecvAndPayDetailTab_NewTemp.IsPrint = 1;
                    m_bllFinDepRecvAndPayDetailTab_New.Update(modelFinDepRecvAndPayDetailTab_NewTemp);
                }
                catch (System.Exception ex)
                {

                }
                
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;
            //m_dt.Clear();
            //m_dt = (DataTable)ultraGrid1.DataSource;
            m_ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }
                    SetUltraGrid1HidderColumnOther(true);
                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                    SetUltraGrid1HidderColumnOther(false);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;
            m_bIsExportAllColumn = true;
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int nIndex = m_nDelbackgroundIndex;
            if (m_nDelbackgroundIndex < 0)
                return;

            backgroundWorker1.ReportProgress(0);
            System.Threading.Thread.Sleep(1);

            UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nDelbackgroundIndex];
            if (null == CurrentUGR)
                return;

            string strNow = DateTime.Now.Date.ToShortDateString();
            string strForder = m_strFolder + strNow;
            if (!Directory.Exists(strForder))//判断是否存在
            {
                Directory.CreateDirectory(strForder);//创建新路径
            }

            string strNo = CurrentUGR.Cells["编号"].Value.ToString();

            DataSet ds = m_bllFinRecvMoneyDetailTab_New.GetList("");
            ultraGrid2.DataSource = ds.Tables[0];

            string strFileName = strForder + @"/" + "总财务收款明细表管理_" + strNo + ".xls";
            ultraGridExcelExporter1.Export(ultraGrid2, strFileName);
            backgroundWorker1.ReportProgress(20);
            System.Threading.Thread.Sleep(1);

            ds = m_bllFinCheckInvoiceRecordDetailTab_New.GetFinInvoiceRecordTabInfo("");
            ultraGrid2.DataSource = ds.Tables[0];

            strFileName = strForder + @"/" + "审票记录明细_" + strNo + ".xls";
            ultraGridExcelExporter1.Export(ultraGrid2, strFileName);
            backgroundWorker1.ReportProgress(40);
            System.Threading.Thread.Sleep(1);

            ds = m_bllFinRecvMoneyAuxiliaryTab_New.GetFinRecvMoneyAuxiliaryInfo("FinRecvMoneyDetailTab_New.isNotJoinBackTax = 0");
            ultraGrid2.DataSource = ds.Tables[0];

            strFileName = strForder + @"/" + "收款明细补充表_" + strNo + ".xls";
            ultraGridExcelExporter1.Export(ultraGrid2, strFileName);
            backgroundWorker1.ReportProgress(60);
            System.Threading.Thread.Sleep(1);

            ds = m_bllFinCheckInvoiceRecordDetailAuxiliaryTab_New.GetCheckInvoiceRecordDetailAuxiliaryInfo("");
            ultraGrid2.DataSource = ds.Tables[0];

            strFileName = strForder + @"/" + "审票明细补充表_" + strNo + ".xls";
            ultraGridExcelExporter1.Export(ultraGrid2, strFileName);
            backgroundWorker1.ReportProgress(80);
            System.Threading.Thread.Sleep(1);

            ds = m_bllFinDepRecvAndPayDetailTab_New.GetList("");
            ultraGrid2.DataSource = ds.Tables[0];

            strFileName = strForder + @"/" + "部门收款及付款明细表管理_" + strNo + ".xls";
            ultraGridExcelExporter1.Export(ultraGrid2, strFileName);
            backgroundWorker1.ReportProgress(100);
            System.Threading.Thread.Sleep(1);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            m_SQLStringList.Clear();
            m_arrayList.Clear();
            int nIndex = m_nDelbackgroundIndex;
            if (m_nDelbackgroundIndex < 0)
                return;

            DialogResult dr = MessageBox.Show("确实要删除该记录么!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.Cancel)
            {
                this.labelProcess.Visible = false;
                this.progressBarBackup.Visible = false;
                return;
            }

            this.labelProcess.Visible = false;
            this.progressBarBackup.Visible = false;

            UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nDelbackgroundIndex];
            int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
            DeleteBackTaxRecord(nSelectFinRecvMoneyDetailTab_NewID);

            if (m_nDelbackgroundIndex >= 0)
            {
                if (ultraGrid1.ActiveRow != null)
                {
                    ultraGrid1.ActiveRow.Delete(false);
                }
            }
            else
            {
                MessageBox.Show("请选中要删除的记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBarBackup.Value = e.ProgressPercentage;
            this.labelProcess.Text = "进度：" + e.ProgressPercentage.ToString() + "%";
        }
    }
}
